package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService{
    
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void deleteById(Long id) {

        employeeMapper.deleteRelation(id);

        employeeMapper.deleteById(id);
    }

    @Override
    public void insert(Employee employee, Long[] ids) {

        //  MD5加密
        //  第一个参数，需要加密的属性
        //  第二个从参数，加盐
        //  第三个参数，加密次数
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName(), 1);
        employee.setPassword(md5Hash.toString());

        employeeMapper.insert(employee);

        if (ids != null && ids.length > 0) {
        /*
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        */
            employeeMapper.insertBatchRelation(employee.getId(), ids);
        }
    }

    @Override
    public Employee selectById(Long id) {
        return employeeMapper.selectById(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void updateById(Employee employee, Long[] ids) {
        employeeMapper.updateById(employee);

        employeeMapper.deleteRelation(employee.getId());

        if (ids != null && ids.length > 0) {
        /*
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        */
            employeeMapper.insertBatchRelation(employee.getId(), ids);
        }
    }

    @Override
    public PageInfo<Employee> query(EmployeeQueryObject qo) {

        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());

        //  查询满足条件的每页显示的数据
        List<Employee> employees = employeeMapper.queryForList(qo);
        //  返回一个结果集
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String username, String password) {

        if (!StringUtils.hasLength(username)) {
            throw new RuntimeException("账户不能为空");
        }

        if (!StringUtils.hasLength(password)) {
            throw new RuntimeException("密码不能为空");
        }

        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) {
            throw new RuntimeException("账户或密码错误");
        }

        return employee;
    }

    @Override
    public void setNewPassword(Long id, String newPassword) {
        employeeMapper.setNewPassword(id, newPassword);
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public void deleteBatchRelation(Long[] ids) {
        employeeMapper.deleteBatchRelation(ids);
    }

    @Override
    public Employee checkName(String name) {
        return employeeMapper.checkName(name);
    }

    @Override
    public Workbook exportXls() {

        //  创建表格文件
        HSSFWorkbook workbook = new HSSFWorkbook();

        //  创建当前工作蒲
        HSSFSheet sheet = workbook.createSheet("员工白名单");
        //  设置行
        HSSFRow row = sheet.createRow(0);
        //  设置单元格内容
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        //  查询所有员工
        List<Employee> employees = employeeMapper.selectAll();

        //  遍历查询到的员工集合
        for (int i = 0; i < employees.size(); i++) {
            //  通过索引遍历每个员工对象
            Employee employee = employees.get(i);
            //  在循环中设置行
            row = sheet.createRow(i + 1);
            //  把每个员工的数据设置到行中
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }

        //  返回表格文件
        return workbook;
    }

    @Override
    public void importXls(Workbook workbook) {
        //  获取第一页工作蒲
        Sheet rows = workbook.getSheetAt(0);
        //  获取最后一行的索引值
        int lastRowNum = rows.getLastRowNum();
        //  遍历
        for (int i = 1; i <= lastRowNum ; i++) {
            //  遍历每一行
            Row row = rows.getRow(i);
            //  创建员工对象
            Employee employee = new Employee();

            //  判断用户名是否为空
            if (!StringUtils.hasLength(row.getCell(0).getStringCellValue().trim())) {
                //  若为空，直接跳出当前循环
                //  进行下次循环
                continue;
            }

            //  将从行中获取到的单元格的用户名设置到员工对象中
            employee.setName(row.getCell(0).getStringCellValue());
            //  将从行中获取到的单元格的邮箱设置到员工对象中
            employee.setEmail(row.getCell(1).getStringCellValue());

            //  判断从行中获取到的单元格的内容类型和String进行比较
            if (row.getCell(2).getCellType().equals(CellType.STRING)) {
                //  若是String类型，则获取文本类型的年龄数据设置进去
                employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            } else {
                //  若不是String类型，则获取数字类型的年龄数据设置进去
                employee.setAge((int)row.getCell(2).getNumericCellValue());
            }

            //  设置密码
            employee.setPassword("1");
            //  调用本类的插入方法
            this.insert(employee, null);
        }
    }

    @Override
    public void updateByStatus(Long id, boolean status) {
        employeeMapper.updateByStatus(id, status);
    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectByRoleSn(sns);
    }

}
